# The search controller contains the following actions:
# [#show_results] performs a full-text search using Ferret
class SearchController < ApplicationController

  # show a panel for complex queries
  def advanced_search
    @special_fields=params[:special][:fields].to_i if params[:special] #get number of specialized fields to show up in the form
    @special_fields ||= 3
    @opts_for_fields=[3,6,9,12] # number of specialized fields
    @opts_for_type=[['(ignored)'.t,'ignore'],['tag'.t,'tag_list:'],['filename'.t,'filename:'],['content'.t,'text:'],['(search all versions)'.t,'version:*'],['(only my files)'.t,'user_id:'+session[:user_id].to_s]]
    if f_id=params[:folder_id]
      @opts_for_type+=[['(only current folder)'.t,'folder_id:'+ f_id]] 
      ac=Folder.find(f_id).allchildren
      unless ac.empty?
        ac_s=([f_id] + ac).select{|f| @logged_in_user.can_read(f)}.map{|f| 'folder_id:'+f.to_s}.join(' OR ')
        @opts_for_type+=[['(in current folder)'.t,"(#{ac_s})"]]
      end
    end
  end

  # Performs a full-text search using Ferret.
  # Only the files that can be read are returned.
  def show_results
  # TODO: consider the implications of removing the request=post requirement
    @search_query = params[:search][:query]
    @options = params[:search][:options] || {:limit => :all}
    
    #integrate advanced search queries if present
    if s=params[:special]
      s.size.times do |i|
        stype=s[i.to_s][:type]
        sterm=s[i.to_s][:term]
        if stype[-1].to_i.chr==':'
          @search_query += ' '+ stype +'"'+sterm+'"' unless sterm==''
        else # not ending with : means the type has already the argument, so ignore sterm
          @search_query += ' '+ stype unless stype=='ignore'
        end
      end
    end
    @result = [] # array to hold the results

    # Search with Ferret in both Folder (name)
    # and Myfile (filename and text)
    # multi search is buggy or inefficient as version is not a field in folder
    Folder.find_by_contents(@search_query,@options).each {|hit|
        @result << hit if @logged_in_user.can_read(hit.id)}
    default_version=' version:0'
    purgequotes=@search_query.gsub(/\".*?\"/,'') # look among search parameters only
    default_version='' if purgequotes.index('version:') #ignore default if version params exist
    Myfile.find_by_contents(@search_query + default_version,@options).each {|hit|
        @result << hit if @logged_in_user.can_read(hit.folder.id)}
  end
end